'use strict'

const qr = require('qr-image')
const { Controller } = require('egg')

class QrController extends Controller {
  /**
 * @api {GET} /qrcode [二维码] 生成
 * @apiDescription 二维码生成
 * @apiGroup Tool
 * @apiVersion 0.0.0
 *
 * @apiParam {String} text 二维码文本（url可以使用encodeURIComponent编码）
 * @apiParam {String} [margin] 二维码边距 
 * @apiParam {String} [type=png] 二维码类型 svg、png
 * 
 * @apiSuccess {Number} code 状态码 0 代表无错误 1代表有错误
 * @apiSuccess {String} msg  success
 * @apiSuccess {Object} data
 *
 * @apiParamExample {json} 请求样例：
 * http://127.0.0.1:7001/api/qrcode?text=http://127.0.0.1:7001
 * http://127.0.0.1:7001/api/qrcode?text=http%3A%2F%2F127.0.0.1%3A7001%3Fa%3D1%26b%3D2
 *
 * @apiSuccessExample {json} Success-Response:
    {
        "code": 0,
        "msg": "success",
    }
 */
  createQRCode() {
    const { ctx } = this
    const { query } = ctx
    const { text } = query

    if (!text || text == '') throw '无效内容'

    const content = decodeURIComponent(query.text)

    console.log('[API] 二维码生成 ' + content)

    try {
      var img = qr.image(content, {
        size: 10,
        margin: Number(query.margin) || 0,
        type: query.type || 'png',
      })

      ctx.type = 'image/png'
      ctx.body = img
    } catch (e) {
      ctx.type = 'text/html;charset=utf-8'
      ctx.body = '<h1>414 Request-URI Too Large</h1>'
    }
  }
}

module.exports = QrController
